<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="" cellpadding="10" cellspacing="0" v-if="student.length">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in student" :key="item.index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      student: [
        {
          id: 1,
          uname: 'TOM',
          age: 18,
          gender: '男',
        },
        {
          id: 2,
          uname: '小明',
          age: 20,
          gender: '男',
        },
        {
          id: 3,
          uname: '翠花',
          age: 18,
          gender: '女',
        },
      ],
      indeId: '',
      uname: '',
      age: '',
      gender: '',
      flag: false,
    }
  },

  methods: {
    // 添加
    add() {
      if (this.flag) {
        this.student[this.indeId].uname = this.uname
        this.student[this.indeId].age = this.age
        this.student[this.indeId].gender = this.gender
        this.uname = ''
        this.age = ''
        this.gender = ''
        this.flag = !this.flag
      } else if (this.uname && this.age && this.gender) {
        if (this.age >= 1) {
          const students = {
            id: this.index + 1,
            uname: this.uname,
            age: this.age,
            gender: this.gender,
          }

          this.student.push(students)
          this.uname = ''
          this.age = ''
          this.gender = ''
        } else {
          alert('请输入正确年龄')
        }
      } else {
        alert('请输入必填项')
      }
    },

    //  删除
    del(index) {
      // console.log(index)
      this.student.splice(index, 1)
     
    },

    // 编辑
    edit(index) {
      this.uname = this.student[index].uname
      this.age = this.student[index].age
      this.gender = this.student[index].gender
      this.indeId = index
      this.flag = true
    },
  },
}
</script>
